package com.sgai.zero_robot.ui.control;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.sgai.zero_robot.core.Config.*;
import static com.sgai.zero_robot.utils.LogUtil.rootPath;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgai.zero_robot.App;
import com.sgai.zero_robot.R;
import com.sgai.zero_robot.base.BaseActivity;
import com.sgai.zero_robot.base.BaseViewModel;
import com.sgai.zero_robot.core.RobotManager;
import com.sgai.zero_robot.core.RobotManagerFactory;
import com.sgai.zero_robot.core.callback.AlarmCallback;
import com.sgai.zero_robot.core.callback.BatteryCallback;
import com.sgai.zero_robot.core.callback.ConfigCallback;
import com.sgai.zero_robot.core.callback.RobotCallback;
import com.sgai.zero_robot.core.callback.SparkForkCallback;
import com.sgai.zero_robot.database.ZeroDetectionEntity;
import com.sgai.zero_robot.database.ZeroDetectionRepository;
import com.sgai.zero_robot.databinding.ActivityZeroControlBinding;
import com.sgai.zero_robot.pojo.AlarmInfo;
import com.sgai.zero_robot.pojo.ZeroListInfo;
import com.sgai.zero_robot.pop.AlarmDialog;
import com.sgai.zero_robot.pop.SettingPopupWindow;
import com.sgai.zero_robot.pop.SettingVideoView;
import com.sgai.zero_robot.ui.history.RunnableCallBack;
import com.sgai.zero_robot.ui.history.ZeroHistoryActivity;
import com.sgai.zero_robot.utils.BatteryHelper;
import com.sgai.zero_robot.utils.LogUtil;
import com.sgai.zero_robot.utils.ThreadPoolUtils;
import com.sgai.zero_robot.utils.ZeroUtils;
import com.sgai.zero_robot.utils.record.RecorderConfig;
import com.sgai.zero_robot.utils.record.ScreenRecordService;
import com.siyi.imagetransmission.connection.ConnectionListener;
import com.siyi.imagetransmission.connection.ConnectionManager;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class ZeroControlActivity extends BaseActivity<ActivityZeroControlBinding, BaseViewModel> implements View.OnClickListener {
    private String cm = "cm";
    private String tiankong = "天空";
    private String waice = "外侧";
    private String dimian = "地面";
    private String neice = "内侧";
    private String hasPark = "有火花";
    private String noPark = "无火花";
    private String invalid = "";
    private String provinceName;
    private String cityName;
    private String lineName;
    private String towerNum;
    private int install;
    private int phase;
    private int insulatorNum;
    private int insulator;
    private int direction;
    private List<ZeroListInfo> zeroListInfos = new ArrayList<>();
    private ZeroDetectionRepository zeroDetectionRepository;
    private LoadCurrentRunnable loadRunnable;
    private ZeroStateListAdapter zeroListAdapter = new ZeroStateListAdapter();
    private Timer timer;
    private TimerTask timerTask;
    private ScreenRecordService boundService;
    private boolean isBound = false;
    private static final int REQ_MEDIA_PROJECTION = 1001;
    public static boolean isShowLowBatteryLow = false;
    public static boolean isShowLowBatteryHigh = false;
    public static final int low = 40;
    public static final int high = 20;

    private final ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            boundService = ((ScreenRecordService.LocalBinder) service).getService();
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            boundService = null;
            isBound = false;
        }
    };
    private AlarmCallback alarmCallback = new AlarmCallback() {
        @Override
        public void onAlarm(AlarmInfo alarmInfo) {
            LogUtil.e(TAG, "onAlarm: " + alarmInfo);
            if (RobotManagerFactory.getInstance().alarmInfoMap.size()>0){
                mBinding.ivAlarm.setVisibility(VISIBLE);
                mBinding.tvAlarmNum.setVisibility(VISIBLE);
                mBinding.tvAlarmNum.setText(String.valueOf(RobotManagerFactory.getInstance().alarmInfoMap.size()));
                if (mBinding.alarmRoot.getVisibility() == VISIBLE){
                    updateAlarmList();
                }
            }else{
                mBinding.ivAlarm.setVisibility(GONE);
                mBinding.tvAlarmNum.setVisibility(GONE);
                mBinding.alarmRoot.setVisibility(GONE);
            }
        }

        @Override
        public void onInfo(String info) {
            if (infoDialog == null){
                infoDialog = new AlarmDialog(ZeroControlActivity.this);
            }
            infoDialog.setContent(1,"警告",info);
            if (!infoDialog.isShowing()){
                infoDialog.show();
            }
        }
    };
    AlarmDialog infoDialog;
    private SparkForkCallback sparkForkCallback = new SparkForkCallback() {

        @Override
        public void onValidTestValue(String value) {
            LogUtil.e(TAG, "onValidTestValue: " + value);
            ThreadPoolUtils.getInstance().addParallelTask(new Runnable() {
                @Override
                public void run() {
                    if (zero.equals(value)) {
                        saveFront();
                    } else if (one.equals(value)) {
                        saveBack();
                    } else if (two.equals(value)) {
                        saveFront();
                        saveBack();
                    }
                }
            });
        }
    };
    private RobotCallback robotCallback = new RobotCallback() {
        @Override
        public void onPitch(String pitchValue) {
            LogUtil.e(TAG,"onPitch  "+pitchValue);
            if (!TextUtils.isEmpty(pitchValue)&&!"-".equals(pitchValue)) {
                double i = Double.parseDouble(pitchValue);
                double t = i / 10;
                mBinding.tvPitch.setText("俯仰：" + String.format("%.1f", t));
            }
        }

        @Override
        public void onRoll(String rollValue) {
            LogUtil.e(TAG,"onRoll  "+rollValue);
            if (!TextUtils.isEmpty(rollValue)&&!"-".equals(rollValue)){
                double i = Double.parseDouble(rollValue);
                double t = i / 10;
                if (!TextUtils.isEmpty(rollValue)) {
                    mBinding.tvRoll.setText("滚动：" + String.format("%.1f", t));
                }
            }
        }

        @Override
        public void onYaw(String yawValue) {
            LogUtil.e(TAG,"onYaw  "+yawValue);
            if (!TextUtils.isEmpty(yawValue)&&!"-".equals(yawValue)) {
                double i = Double.parseDouble(yawValue);
                double t = i / 10;
                mBinding.tvYaw.setText("偏航：" + String.format("%.1f", t));
            }
        }

    };
    private BatteryCallback batteryCallback = new BatteryCallback() {
        @Override
        public void onBattery(int battery) {
            initRobotBattery(battery,true);
        }

        @Override
        public void onVoltage(String voltage) {

        }

        @Override
        public void onCurrent(String current) {

        }

        @Override
        public void onHealthy(String healthy) {

        }

        @Override
        public void onCellTemperature(String temperature) {

        }

        @Override
        public void onMOSTemperature(String temperature) {

        }

        @Override
        public void onBMSSystem1(String state) {

        }

        @Override
        public void onBMSSystem2(String state) {

        }

        @Override
        public void onCellVoltage1(String voltage) {

        }

        @Override
        public void onCellVoltage2(String voltage) {

        }

        @Override
        public void onCellVoltage3(String voltage) {

        }

        @Override
        public void onCellVoltage4(String voltage) {

        }

        @Override
        public void onCount(String count) {

        }
    };
    private ConfigCallback configCallback = new ConfigCallback() {
        @Override
        public void onState(String adjValue) {
            if (one.equals(adjValue)){
                showToast("开始配置");
            }else if (zero.equals(adjValue)){
                showToast("保存成功");
            }
        }
    };
    private SettingPopupWindow settingPopupWindow;
    private VideoPlayer oneVideoPlayer,twoVideoPlayer;


    private void insertEntity(ZeroListInfo zeroListInfo, int currentInsulator, ZeroDetectionEntity zeroDetectionEntity) {
        if (currentInsulator == 1) {
            zeroListInfo.setLeft(zeroDetectionEntity);
        } else if (currentInsulator == 2) {
            zeroListInfo.setMid(zeroDetectionEntity);
        } else if (currentInsulator == 3) {
            zeroListInfo.setRight(zeroDetectionEntity);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ConnectionManager.getInstance(this).checkConnectWithIntent(null);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        ConnectionManager.getInstance(this).checkConnectWithIntent(intent);
    }

    @Override
    public void initViews(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mBinding.rvAlarm.setLayoutManager(layoutManager);
        mBinding.rvAlarm.setAdapter(alarmMessageAdapter);
        provinceName = getIntent().getStringExtra("provinceName");
        cityName = getIntent().getStringExtra("cityName");
        lineName = getIntent().getStringExtra("lineName");
        towerNum = getIntent().getStringExtra("towerNum");
        install = getIntent().getIntExtra("install", 1);
        phase = getIntent().getIntExtra("phase", 1);
        insulatorNum = getIntent().getIntExtra("insulatorNum", 1);
        insulator = getIntent().getIntExtra("insulator", 2);
        direction = getIntent().getIntExtra("direction", 1);
        mBinding.tvTitle.setText(lineName);
        initPlayer();
        zeroDetectionRepository = new ZeroDetectionRepository();
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(new ColorDrawable(Color.WHITE));
        mBinding.rvHistory.addItemDecoration(dividerItemDecoration);
        DividerItemDecoration dividerItemDecoration1 = new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL);
        dividerItemDecoration1.setDrawable(new ColorDrawable(Color.WHITE));
        mBinding.rvHistory.addItemDecoration(dividerItemDecoration1);
        mBinding.rvHistory.setLayoutManager(new GridLayoutManager(this, 4));
        mBinding.rvHistory.setAdapter(zeroListAdapter);
        mBinding.tvPointFrontAdd.setOnClickListener(this);
        mBinding.tvPointFrontMinus.setOnClickListener(this);
        mBinding.tvPointBackAdd.setOnClickListener(this);
        mBinding.tvPointBackMinus.setOnClickListener(this);
        mBinding.ivMore.setOnClickListener(this);
        mBinding.ivAlarm.setOnClickListener(this);
        mBinding.ivTakePhoto.setOnClickListener(this);
        mBinding.ivHistory.setOnClickListener(this);
        mBinding.ivCallback.setOnClickListener(this);
        mBinding.cvSmallVideoRoot.setOnClickListener(this);
        RobotManagerFactory.getInstance().addAlarmCallback(alarmCallback);
        RobotManagerFactory.getInstance().addSparkForkCallback(sparkForkCallback);
        RobotManagerFactory.getInstance().addRobotCallback(robotCallback);
        RobotManagerFactory.getInstance().addConfigCallback(configCallback);
        RobotManagerFactory.getInstance().addBatteryCallback(batteryCallback);
    }

    @Override
    public void loadData() {
        initFrontLaserRanging(RobotManagerFactory.getInstance().frontLaserRanging);
        initBackLaserRanging(RobotManagerFactory.getInstance().backLaserRanging);
        initFrontSwingMotor(RobotManagerFactory.getInstance().frontSwingMotor);
        initBackSwingMotor(RobotManagerFactory.getInstance().backSwingMotor);
        initFrontSpark(RobotManagerFactory.getInstance().frontSpark);
        initBackSpark(RobotManagerFactory.getInstance().backSpark);
        initBoardTemperature(RobotManagerFactory.getInstance().boardTemperature);
        initMobileBattery(BatteryHelper.getInstance().percent);
        initRobotBattery(RobotManagerFactory.getInstance().battery,false);
        SettingVideoView.recordVideo.setValue(false);
        SettingVideoView.recordVideo.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (Boolean.TRUE.equals(aBoolean)) {
                    startRecording();
                } else {
                    stopRecording();
                }
            }
        });
        showLoading("正在加载...");
        loadRunnable = new LoadCurrentRunnable(zeroDetectionRepository, zeroListInfos -> runOnUiThread(() -> {
            dismissLoading();
            if (zeroListInfos != null) {
                ZeroControlActivity.this.zeroListInfos = zeroListInfos;
                List<String> defaultList = getDefaultList();
                for (ZeroListInfo zeroListInfo1 : zeroListInfos) {
                    addContent(defaultList, zeroListInfo1);
                }
                zeroListAdapter.setData(defaultList);
                zeroListAdapter.notifyDataSetChanged();
                mBinding.rvHistory.scrollToPosition(defaultList.size() - 1);
            }
        }), lineName, towerNum, install, phase);
        ThreadPoolUtils.getInstance().addSerialTask(loadRunnable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTimer();
    }

    @Override
    public void onClick(View view) {
        if (view == mBinding.tvPointFrontAdd) {
            mBinding.tvPointFront.setText(add(mBinding.tvPointFront));
        } else if (view == mBinding.tvPointFrontMinus) {
            mBinding.tvPointFront.setText(subtract(mBinding.tvPointFront));
        } else if (view == mBinding.tvPointBackAdd) {
            mBinding.tvPointBack.setText(add(mBinding.tvPointBack));
        } else if (view == mBinding.tvPointBackMinus) {
            mBinding.tvPointBack.setText(subtract(mBinding.tvPointBack));
        } else if (view == mBinding.ivMore) {
            if (settingPopupWindow == null) {
                settingPopupWindow = new SettingPopupWindow(this);
            }
            if (settingPopupWindow.isShowing()) {
                return;
            }
            settingPopupWindow.showAtLocation(ZeroControlActivity.this, mBinding.getRoot(), Gravity.RIGHT, 0, 0);
        } else if (view == mBinding.ivAlarm){
            if (mBinding.alarmRoot.getVisibility() == VISIBLE){
                mBinding.alarmRoot.setVisibility(GONE);
            }else{
                mBinding.alarmRoot.setVisibility(VISIBLE);
                updateAlarmList();
            }
        }else if (view == mBinding.ivTakePhoto){
            TextureView textureView ;
            if (oneInMax){
                textureView = oneVideoPlayer.getTextureView();
            }else{
                textureView = twoVideoPlayer.getTextureView();
            }
            //拍照
            if (!textureView.isAvailable()) {
               showAlarm(2,"出错了","拍照失败",null);
                return;
            }
            showLoading("正在拍照...");
            Bitmap bitmap = Bitmap.createBitmap(textureView.getWidth(), textureView.getHeight(), Bitmap.Config.ARGB_8888);
            textureView.getBitmap(bitmap);
            File moviesDir = new File(rootPath + "photo/");
            File file = new File(moviesDir, System.currentTimeMillis()+".png");
            saveBitmapRunnable =  new SaveBitmapRunnable(file, bitmap, new RunnableCallBack<String>() {
                @Override
                public void onResult(String s) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoading();
                            showAlarm(2,"保存图片","图片保存成功，路径是"+s,null);
                        }
                    });
                }
            });
            ThreadPoolUtils.getInstance().addParallelTask(saveBitmapRunnable);
        }else if (view == mBinding.ivHistory){
            startActivity(new Intent(ZeroControlActivity.this, ZeroHistoryActivity.class));
        }else if (view == mBinding.ivCallback){
            finish();
        }else if (view == mBinding.cvSmallVideoRoot){
            mBinding.flMaxVideoRoot.removeAllViews();
            mBinding.flSmallVideoRoot.removeAllViews();
            if (oneInMax){
                twoVideoPlayer.showStroke(false);
                oneVideoPlayer.showStroke(true);
                mBinding.flMaxVideoRoot.addView(twoVideoPlayer, 0);
                mBinding.flSmallVideoRoot.addView(oneVideoPlayer, 0);
            }else{
                twoVideoPlayer.showStroke(true);
                oneVideoPlayer.showStroke(false);
                mBinding.flMaxVideoRoot.addView(oneVideoPlayer, 0);
                mBinding.flSmallVideoRoot.addView(twoVideoPlayer, 0);
            }
            oneInMax = !oneInMax;
        }
    }
    private SaveBitmapRunnable saveBitmapRunnable ;
    private AlarmMessageAdapter alarmMessageAdapter
             = new AlarmMessageAdapter();
    private void updateAlarmList(){
        List<String> list = new ArrayList<>(RobotManagerFactory.getInstance().alarmInfoMap.size());
        Iterator<Map.Entry<String, AlarmInfo>> iterator =
                RobotManagerFactory.getInstance().alarmInfoMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, AlarmInfo> next = iterator.next();
            list.add(next.getValue().getMsg());
        }
        alarmMessageAdapter.setData(list);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_MEDIA_PROJECTION) {
            if (resultCode == RESULT_OK && data != null) {
                RecorderConfig cfg = new RecorderConfig();
                cfg.fileDisplayName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()).toString() + lineName + towerNum + ZeroUtils.getInstall(install) + ZeroUtils.getPhase(phase);
                Intent svc = new Intent(this, ScreenRecordService.class);
                svc.putExtra(ScreenRecordService.EXTRA_RESULT_CODE, resultCode);
                svc.putExtra(ScreenRecordService.EXTRA_DATA_INTENT, data);
                svc.putExtra(ScreenRecordService.EXTRA_CONFIG, cfg);
                ContextCompat.startForegroundService(this, svc);
                bindService(svc, conn, Context.BIND_AUTO_CREATE);
                showToast("开始录制");
            } else {
                showToast("取消录制");
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ConnectionManager.getInstance(ZeroControlActivity.this).release();
        stopRecording();
        SettingVideoView.recordVideo.setValue(false);
        if (settingPopupWindow != null && settingPopupWindow.isShowing()) {
            settingPopupWindow.dismiss();
        }
        if (loadRunnable != null) {
            ThreadPoolUtils.getInstance().removeParallelTask(loadRunnable);
        }
        if (isBound) {
            try {
                unbindService(conn);
            } catch (Exception ignored) {
            }
            isBound = false;
        }
        if (oneVideoPlayer!=null){
            if (oneVideoPlayer.getIndex() == 1){
                ConnectionManager.getInstance(this).notifySurfaceDestroy(oneVideoPlayer.mSurface);
            }else{
                ConnectionManager.getInstance(this).notifySecondSurfaceDestroy(oneVideoPlayer.mSurface);
            }
        }
        if (twoVideoPlayer!=null){
            if (twoVideoPlayer.getIndex() == 1){
                ConnectionManager.getInstance(this).notifySurfaceDestroy(twoVideoPlayer.mSurface);
            }else{
                ConnectionManager.getInstance(this).notifySecondSurfaceDestroy(twoVideoPlayer.mSurface);
            }
        }
        BatteryHelper.getInstance().stop();
        RobotManagerFactory.getInstance().removeAlarmCallback(alarmCallback);
        RobotManagerFactory.getInstance().removeSparkForkCallback(sparkForkCallback);
        RobotManagerFactory.getInstance().removeRobotCallback(robotCallback);
        RobotManagerFactory.getInstance().removeConfigCallback(configCallback);
        RobotManagerFactory.getInstance().removeBatteryCallback(batteryCallback);
    }

    private void stopRecording() {
        if (boundService != null) {
            boundService.stopRecording();
            showToast("已停止并保存到相册/Movies/ScreenRecords");
        }
    }

    private void startRecording() {
        MediaProjectionManager mpm = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mpm.createScreenCaptureIntent(), REQ_MEDIA_PROJECTION);
    }

    private void startTimer() {
        stopTimer();
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initFrontLaserRanging(RobotManagerFactory.getInstance().frontLaserRanging);
                        initBackLaserRanging(RobotManagerFactory.getInstance().backLaserRanging);
                        initFrontSwingMotor(RobotManagerFactory.getInstance().frontSwingMotor);
                        initBackSwingMotor(RobotManagerFactory.getInstance().backSwingMotor);
                        initFrontSpark(RobotManagerFactory.getInstance().frontSpark);
                        initBackSpark(RobotManagerFactory.getInstance().backSpark);
                        initBoardTemperature(RobotManagerFactory.getInstance().boardTemperature);
                        initMobileBattery(BatteryHelper.getInstance().percent);
                        initRobotBattery(RobotManagerFactory.getInstance().battery, false);
                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private void stopTimer() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (timer != null) {
            timer.cancel();
            ;
            timer = null;
        }
    }

    private void initMobileBattery(int percent) {
        mBinding.ivMobileBattery.setImageResource(getMBattery(percent));
//        setBatteryTextColor(mBinding.tvMobileBattery, percent);
    }

    private void initRobotBattery(int percent,boolean isShow) {
        mBinding.ivRobotBattery.setImageResource(getRBattery(percent));
//        setBatteryTextColor(mBinding.tvRobotBattery, percent);
        if (isShow){
            if (high<percent&&percent<=low&&!isShowLowBatteryLow){
                showAlarm(2,"告警","电量低，请谨慎操作!",null);
                isShowLowBatteryLow = true;
                return;
            }
            if (percent<=high&&!isShowLowBatteryHigh){
                showAlarm(2,"严重告警","电量过低，请立即收回机器人!",null);
                isShowLowBatteryHigh = true;
            }
        }
    }

    private void initFrontLaserRanging(String value) {
        if (!TextUtils.isEmpty(value)) {
            if (mBinding.tvForwardDistance.getVisibility() != VISIBLE) {
                mBinding.tvForwardDistance.setVisibility(VISIBLE);
            }
            if (mBinding.ivForwardArrow.getVisibility() != VISIBLE) {
                mBinding.ivForwardArrow.setVisibility(VISIBLE);
            }
            int i = Integer.parseInt(value) / 10;
            mBinding.tvForwardDistance.setText(String.valueOf(i) + cm);
        }
    }

    private void initBackLaserRanging(String value) {
        if (!TextUtils.isEmpty(value)) {
            if (mBinding.tvBackDistance.getVisibility() != VISIBLE) {
                mBinding.tvBackDistance.setVisibility(VISIBLE);
            }
            if (mBinding.ivBackwardArrow.getVisibility() != VISIBLE) {
                mBinding.ivBackwardArrow.setVisibility(VISIBLE);
            }
            int i = Integer.parseInt(value) / 10;
            mBinding.tvBackDistance.setText(String.valueOf(i) + cm);
        }
    }
    private String frontSwingMotor;
    private String backSwingMotor;
    private void initFrontSwingMotor(String value) {
        if (!TextUtils.isEmpty(value)) {
            frontSwingMotor = value;
            if (zero.equals(value)) {
                mBinding.tvFrontDirection.setText(tiankong);
            } else if (one.equals(value)) {
                mBinding.tvFrontDirection.setText(waice);
            } else if (two.equals(value)) {
                mBinding.tvFrontDirection.setText(dimian);
            } else if (three.equals(value)) {
                mBinding.tvFrontDirection.setText(neice);
            }
        }
    }

    private void initBackSwingMotor(String value) {
        if (!TextUtils.isEmpty(value)) {
            backSwingMotor = value;
            if (zero.equals(value)) {
                mBinding.tvBackDirection.setText(tiankong);
            } else if (one.equals(value)) {
                mBinding.tvBackDirection.setText(waice);
            } else if (two.equals(value)) {
                mBinding.tvBackDirection.setText(dimian);
            } else if (three.equals(value)) {
                mBinding.tvBackDirection.setText(neice);
            }
        }
    }

    private void initFrontSpark(String value) {
        if (one.equals(frontSwingMotor)||three.equals(frontSwingMotor)){
            if (one.equals(value)) {
                mBinding.tvFrontState.setText(hasPark);
                mBinding.vFrontState.setBackgroundResource(R.drawable.shape_green_oval);
            } else {
                mBinding.tvFrontState.setText(noPark);
                mBinding.vFrontState.setBackgroundResource(R.drawable.shape_red_oval);
            }
        }else{
            mBinding.tvFrontState.setText(invalid);
            mBinding.vFrontState.setBackgroundResource(R.drawable.shape_gray_oval);
        }
    }

    private void initBackSpark(String value) {
        if (one.equals(backSwingMotor)||three.equals(backSwingMotor)){
            if (one.equals(value)) {
                mBinding.tvBackState.setText(hasPark);
                mBinding.vBackState.setBackgroundResource(R.drawable.shape_green_oval);
            } else {
                mBinding.tvBackState.setText(noPark);
                mBinding.vBackState.setBackgroundResource(R.drawable.shape_red_oval);
            }
        }else{
            mBinding.tvBackState.setText(invalid);
            mBinding.vBackState.setBackgroundResource(R.drawable.shape_gray_oval);
        }
    }

    private void initBoardTemperature(String value) {
        if (!TextUtils.isEmpty(value)) {
            double i = Double.parseDouble(value);
            double t = i / 10;
            mBinding.tvTemperature.setText(String.format("%.1f", t));
        }
    }

    private boolean oneInMax = true;
    private void showDisConnect(int i ,boolean isShow){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (oneVideoPlayer!=null){
                    if (oneVideoPlayer.getIndex() == i){
                        oneVideoPlayer.showDisconnect(isShow);
                    }
                }else  if (twoVideoPlayer!=null){
                    if (twoVideoPlayer.getIndex() == i){
                        twoVideoPlayer.showDisconnect(isShow);
                    }
                }
            }
        });
    }
    private void initPlayer() {
        LogUtil.e(TAG, "initPlayer: ");
        if (App.TYPE== 3){
            ConnectionManager.getInstance(ZeroControlActivity.this).setWirelessUrl("rtsp://admin:12345678a@192.168.144.90:554/Streaming/Channels/101", "rtsp://admin:12345678a@192.168.144.91:554/Streaming/Channels/101");
        }else{
            ConnectionManager.getInstance(ZeroControlActivity.this).setWirelessUrl("rtsp://192.168.144.90:554/user=admin&password=&channel=1&stream=0.sdp?", null);

        }
        ConnectionManager.getInstance(ZeroControlActivity.this).setConnectionListener(new ConnectionListener() {
            @Override
            public void onConnected(int i) {
                LogUtil.e(TAG, "onConnected: " + i);
               showDisConnect(i,false);
            }

            @Override
            public void onDisconnected(int i) {
                LogUtil.e(TAG, "onDisconnected: " + i);
                showDisConnect(i,true);
            }
        });
        if (App.TYPE== 3){
            oneVideoPlayer = new VideoPlayer(this);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            oneVideoPlayer.setLayoutParams(layoutParams);
            oneVideoPlayer.initPlayer(1,false);
            mBinding.flMaxVideoRoot.addView(oneVideoPlayer, 0);

            twoVideoPlayer = new VideoPlayer(this);
            FrameLayout.LayoutParams layoutParams2 = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            twoVideoPlayer.setLayoutParams(layoutParams2);
            twoVideoPlayer.initPlayer(2,true);
            mBinding.flSmallVideoRoot.addView(twoVideoPlayer, 0);
        }else{
            oneVideoPlayer = new VideoPlayer(this);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            oneVideoPlayer.setLayoutParams(layoutParams);
            oneVideoPlayer.initPlayer(1,false);
            mBinding.flMaxVideoRoot.addView(oneVideoPlayer, 0);
            mBinding.cvSmallVideoRoot.setVisibility(GONE);
        }

    }


    private String add(TextView textView) {
        String string = textView.getText().toString();
        int i = Integer.parseInt(string);
        return String.valueOf(i + 1);
    }

    private String subtract(TextView textView) {
        String string = textView.getText().toString();
        int i = Integer.parseInt(string);
        if (i - 1 <= 0) {
            return one;
        }
        return String.valueOf(i - 1);
    }

    private int getCurrentInsulator(String swingMotor) {
        int currentInsulator = -1;
        if (insulatorNum == 1) {
            //如果是单串 只处理内侧 并且内串就是中串
            if (three.equals(swingMotor)) {
                currentInsulator = 2;
            }
        } else if (insulatorNum == 2) {
            //如果是双串 就只有内串和外串了 就看机头朝向了
            if (three.equals(swingMotor)) {
                //内侧就是当前串
                currentInsulator = insulator;
            } else if (one.equals(swingMotor)) {
                //机头朝向高压侧
                if (direction == 1) {
                    //如果是大号侧
                    if (install == 2) {
                        //机器人放在了内串上了 左侧就是外串了
                        if (insulator == 3) {
                            currentInsulator = 1;
                        }
                    } else {
                        //如果是检测小号侧
                        if (insulator == 1) {
                            //如果是放到了外串上  左侧就是内串了
                            currentInsulator = 3;
                        }
                    }
                } else if (direction == 2) {
                    //机头朝向杆塔侧
                    //如果是检测大号册
                    if (install == 2) {
                        //机器人放在了外串上了 左侧就是内串
                        if (insulator == 1) {
                            currentInsulator = 3;
                        }
                    } else {
                        //如果检测小号侧
                        if (insulator == 3) {
                            //如果是放到了内串
                            currentInsulator = 1;
                        }
                    }
                }
            }
        } else {
            if (three.equals(swingMotor)) {
                //内侧就是当前串
                currentInsulator = insulator;
            } else {
                //机头朝向高压侧
                if (direction == 1) {
                    //如果是检测大号侧
                    if (install == 2) {
                        //如果放到外侧串
                        if (insulator == 1) {
                            //就不需要处理了
                        } else if (insulator == 2) {
                            //如果是放到了中串 外侧就是外串
                            currentInsulator = 1;
                        } else if (insulator == 3) {
                            //如果是放到了内串 外侧就是中串
                            currentInsulator = 2;
                        }
                    } else {
                        //如果是检测小号串
                        //如果放到外侧串
                        if (insulator == 1) {
                            //左串就是中串
                            currentInsulator = 2;
                        } else if (insulator == 2) {
                            //如果是放到了中串 外侧就是内串
                            currentInsulator = 3;
                        } else if (insulator == 3) {
                            //如果是放到了内串 就不需要记录了
                        }
                    }
                } else if (direction == 2) {
                    //机头朝向杆塔侧
                    //如果是检测大号侧
                    if (install == 2) {
                        //如果放到外侧串
                        if (insulator == 1) {
                            //左侧就是中串
                            currentInsulator = 2;
                        } else if (insulator == 2) {
                            //如果是放到了中串 外侧就是内串
                            currentInsulator = 3;
                        } else if (insulator == 3) {
                            //如果是放到了内串 就不需要处理了
                        }
                    } else {
                        //如果放到外侧串
                        if (insulator == 1) {
                            //就不需要处理了
                        } else if (insulator == 2) {
                            //如果是放到了中串 外侧就是外串
                            currentInsulator = 1;
                        } else if (insulator == 3) {
                            //如果是放到了内串 外侧就是中串
                            currentInsulator = 2;
                        }
                    }
                }
            }
        }
        return currentInsulator;
    }

    private void saveBack() {
        LogUtil.e(TAG, "saveBack: ");
        save(RobotManagerFactory.getInstance().backSwingMotor, Integer.parseInt(mBinding.tvPointBack.getText().toString()), RobotManagerFactory.getInstance().backSpark);
    }

    private void saveFront() {
        LogUtil.e(TAG, "saveFront: ");
        save(RobotManagerFactory.getInstance().frontSwingMotor, Integer.parseInt(mBinding.tvPointFront.getText().toString()), RobotManagerFactory.getInstance().frontSpark);
    }

    private ZeroListInfo getZeroListInfo(int index) {
        ZeroListInfo zeroListInfoTemp = null;
        if (zeroListInfos == null || zeroListInfos.size() <= 0) {
            return zeroListInfoTemp;
        }
        LogUtil.e(TAG, "getZeroListInfo: " + zeroListInfos.size());
        for (int i = 0; i < zeroListInfos.size(); i++) {
            ZeroListInfo zeroListInfo = zeroListInfos.get(i);
            if (zeroListInfo.getIndex() == index) {
                zeroListInfoTemp = zeroListInfo;
            } else if (zeroListInfo.getIndex() < i) {
                break;
            }
        }
        return zeroListInfoTemp;
    }

    private void save(String swingMotor, int index, String spark) {
        LogUtil.e(TAG, "save: swingMotor:" + swingMotor + "   index:" + index + "   spark:" + spark);
        int currentInsulator = getCurrentInsulator(swingMotor);
        LogUtil.e(TAG, "save: currentInsulator:" + currentInsulator);
        if (currentInsulator == -1) {
            return;
        }
        if (zeroListInfos == null) {
            zeroListInfos = new ArrayList<>();
        }
        ZeroDetectionEntity zeroDetectionEntity = new ZeroDetectionEntity(provinceName, cityName, lineName, towerNum, install, phase, currentInsulator,
                index, System.currentTimeMillis(), one.equals(spark) ? 1 : 0);
        LogUtil.e(TAG, "save: zeroDetectionEntity:" + zeroDetectionEntity);
        ZeroListInfo zeroListInfo = getZeroListInfo(index);
        LogUtil.e(TAG, "save: zeroListInfo:" + zeroListInfo);
        if (zeroListInfo == null) {
            zeroListInfo = new ZeroListInfo();
            zeroListInfo.setIndex(index);
            for (int k = 0; k < 3; k++) {
                int value = k + 1;
                if (value == currentInsulator) {
                    insertEntity(zeroListInfo, value, zeroDetectionEntity);
                } else {
                    insertEntity(zeroListInfo, value, null);
                }
            }
            zeroListInfos.add(zeroListInfo);
            zeroListInfos.sort(Comparator.comparingInt(ZeroListInfo::getIndex));
        } else {
            if (currentInsulator == 1) {
                zeroListInfo.setLeft(zeroDetectionEntity);
            } else if (currentInsulator == 2) {
                zeroListInfo.setMid(zeroDetectionEntity);
            } else if (currentInsulator == 3) {
                zeroListInfo.setRight(zeroDetectionEntity);
            }
        }
        zeroDetectionRepository.insertZeroDetection(zeroDetectionEntity);
        final ZeroListInfo temp = zeroListInfo;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int i = (zeroListInfos.indexOf(temp) + 1) * 4;
                List<String> defaultList = getDefaultList();
                for (ZeroListInfo zeroListInfo1 : zeroListInfos) {
                    addContent(defaultList, zeroListInfo1);
                }
                zeroListAdapter.setData(defaultList);
                zeroListAdapter.notifyDataSetChanged();
                if (i > defaultList.size()) {
                    i = defaultList.size();
                } else if (i < 0) {
                    i = 0;
                }
                mBinding.rvHistory.scrollToPosition(i);
            }
        });
    }

    private void addContent(List<String> defaultList, ZeroListInfo zeroListInfo) {
        defaultList.add(String.valueOf(zeroListInfo.getIndex()));
        defaultList.add(getContent(zeroListInfo.getLeft()));
        defaultList.add(getContent(zeroListInfo.getMid()));
        defaultList.add(getContent(zeroListInfo.getRight()));
    }

    private String getContent(ZeroDetectionEntity zeroDetectionEntity) {
        if (zeroDetectionEntity == null){
            return "/";
        }
        if (zeroDetectionEntity.getState() == -1) {
            return "/";
        } else if (zeroDetectionEntity.getState() == 0) {
            return "0";
        } else if (zeroDetectionEntity.getState() == 1) {
            return "1";
        } else {
            return "/";
        }
    }

    private List<String> getDefaultList() {
        List<String> list = new ArrayList<>();
        list.add("索引");
        list.add("外串");
        list.add("中串");
        list.add("内串");
        return list;
    }
}